import java.util.Arrays;

public class InsertionSort {
    public static void main(String[] args) {
        int[] a = {9,3,4,1,6,8,1,2};
        System.out.println(Arrays.toString(a));
        insertSort(a);
        System.out.println(Arrays.toString(a));
    }
    //递归版
    public static void insert(int[] a, int low){
        if (low==a.length){
            return;
        }
        int t = a[low];
        int i = low-1;
        while (i>=0 && a[i] > t){
            a[i+1] = a[i];
            i--;
        }
        if (i+1!=low){
            a[i+1] = t;
        }
        insert(a,low+1);
    }

    //非递归
    public static void insertSort(int[] a){
        for (int low = 1; low < a.length; low++){
            int t = a[low];
            int i = low-1;
            while (i>=0 && a[i] > t){
                a[i+1] = a[i];
                i--;
            }
            if (i+1!=low){
                a[i+1] = t;
            }
        }
    }
}
